import sys

import facade
from parsel import Selector
from xjlibrary.our_file_dir import BaseDir

curPath = BaseDir.get_file_dir_absolute(__file__)
configfile = BaseDir.get_new_path(curPath, "db.ini")


class DownCover(object):

    def __init__(self):
        self.Baseurl = "http://yuntu.io/list?keyword={}"
        self.headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Cache-Control": "no-cache",
            "Host": "yuntu.io",
            "Pragma": "no-cache",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36"
        }
        self.logger = facade.get_streamlogger()
        self.mysqlutils = facade.MysqlUtiles(configfile,
                                             "db",
                                             logger=self.logger)

    def down_cover(self, isbn13):
        url = self.Baseurl.format(isbn13)
        BoolResult, errString, r = facade.BaseRequest(url,
                                                      headers=self.headers,
                                                      timeout=(30, 60))
        if BoolResult:
            if r.text.find("很抱歉，没有找到相关搜索结果！") > -1:
                sql = "update isbncover set url='-1',stat=1 where isbn13='{}'".format(isbn13)
                self.mysqlutils.ExeSqlToDB(sql)

            else:
                select = Selector(text=r.text)
                count = select.xpath('//*[@id="item-list"]/div[@class="box-featured"]')

                if len(count) != 1:
                    # self.logger.info("出现不是1的搜索结果")
                    # sql = "update isbncover set stat=-1 where isbn13='{}'".format(isbn13)
                    # self.mysqlutils.ExeSqlToDB(sql)
                    srcs = select.xpath('//*[@id="item-list"]/div/div/div/a/img/@src').getall()
                    sets = set()
                    for url in srcs:
                        sets.add(url)
                    if len(sets) > 1:
                        self.logger.info("出现不是1的搜索结果")
                    for url in sets:
                        if url.find(isbn13) > -1:
                            sql = "update isbncover set url='{}',stat=1 where isbn13='{}'".format(url, isbn13)
                            self.mysqlutils.ExeSqlToDB(sql)
                else:
                    src = select.xpath('//*[@id="item-list"]/div/div/div/a/img/@src').get()
                    print(src)
                    sql = "update isbncover set url='{}',stat=1 where isbn13='{}'".format(src, isbn13)
                    self.mysqlutils.ExeSqlToDB(sql)
        else:
            self.logger.info("下载失败")

    def select(self):
        sql = "select isbn13 from isbncover where stat=0 ORDER BY RAND() limit 1000"
        rows = self.mysqlutils.SelectFromDB(sql)
        if rows:
            for row in rows:
                isbn13 = row[0]
                self.down_cover(isbn13)
        else:
            return "break"


if __name__ == "__main__":
    down = DownCover()
    while True:
        results = down.select()
        if results == "break":
            break
